import { ref, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { usePersonaStore } from "@/stores/persona";
import { useUserStore } from "@/stores/user";
import { personaApi } from "@/api/services";
import type {
  Persona,
  PersonaConfig,
  CreatePersonaRequest,
  UpdatePersonaRequest,
  PersonaSearchOptions,
} from "@/types/persona";
import { PERSONA_TYPES, PERSONA_TAGS, ROUTES } from "@/constants";
import { debounce } from "@/utils";

/**
 * 人格相关的组合式函数
 */
export function usePersona() {
  const router = useRouter();
  const personaStore = usePersonaStore();
  const userStore = useUserStore();

  // 响应式状态
  const isLoading = ref(false);
  const isSaving = ref(false);
  const error = ref<string | null>(null);
  const searchQuery = ref("");
  const selectedTags = ref<string[]>([]);
  const selectedType = ref<string | null>(null);
  const sortBy = ref<string>("popularity");
  const sortOrder = ref<"asc" | "desc">("desc");

  // 计算属性
  const personas = computed(() => personaStore.personas);
  const currentPersona = computed(() => personaStore.currentPersona);
  const favoritePersonas = computed(() => personaStore.favoritePersonas);
  const recentPersonas = computed(() => personaStore.recentPersonas);
  const myPersonas = computed(() => personaStore.myPersonas);
  const hasMorePersonas = computed(() => personaStore.hasMorePersonas);
  const totalPersonas = computed(() => personaStore.totalPersonas);

  // 过滤后的人格列表
  const filteredPersonas = computed(() => {
    let result = personas.value;

    // 按类型过滤
    if (selectedType.value) {
      result = result.filter((p) => p.type === selectedType.value);
    }

    // 按标签过滤
    if (selectedTags.value.length > 0) {
      result = result.filter((p) =>
        selectedTags.value.some((tag) => p.tags?.includes(tag)),
      );
    }

    // 按搜索关键词过滤
    if (searchQuery.value.trim()) {
      const query = searchQuery.value.toLowerCase().trim();
      result = result.filter(
        (p) =>
          p.name.toLowerCase().includes(query) ||
          p.description.toLowerCase().includes(query) ||
          p.tags?.some((tag) => tag.toLowerCase().includes(query)),
      );
    }

    return result;
  });

  /**
   * 加载人格列表
   */
  const loadPersonas = async (options: PersonaSearchOptions = {}) => {
    try {
      isLoading.value = true;
      error.value = null;

      const searchOptions = {
        page: options.page || 1,
        limit: options.limit || 20,
        query: searchQuery.value || options.query,
        type: selectedType.value || options.type,
        tags: selectedTags.value.length > 0 ? selectedTags.value : options.tags,
        sortBy: sortBy.value || options.sortBy,
        sortOrder: sortOrder.value || options.sortOrder,
        ...options,
      };

      const response = await personaApiService.getPersonas(searchOptions);

      if (response.success) {
        if (searchOptions.page === 1) {
          personaStore.setPersonas(response.data.personas);
        } else {
          personaStore.addPersonas(response.data.personas);
        }

        personaStore.setHasMorePersonas(response.data.hasMore);
        personaStore.setTotalPersonas(response.data.total);

        return { success: true, data: response.data };
      } else {
        error.value = response.message || "加载人格失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "加载人格失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 搜索人格（防抖）
   */
  const searchPersonas = debounce(async (query: string) => {
    searchQuery.value = query;
    await loadPersonas({ page: 1 });
  }, 300);

  /**
   * 加载人格详情
   */
  const loadPersona = async (personaId: string) => {
    try {
      isLoading.value = true;
      error.value = null;

      const response = await personaApiService.getPersona(personaId);

      if (response.success) {
        const persona = response.data;
        personaStore.updatePersona(persona);
        personaStore.setCurrentPersona(persona);

        // 添加到最近访问
        personaStore.addToRecent(persona);

        return { success: true, data: persona };
      } else {
        error.value = response.message || "加载人格失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "加载人格失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 创建人格
   */
  const createPersona = async (data: CreatePersonaRequest) => {
    try {
      isSaving.value = true;
      error.value = null;

      const response = await personaApiService.createPersona(data);

      if (response.success) {
        const persona = response.data;
        personaStore.addPersona(persona);
        personaStore.addToMyPersonas(persona);

        // 跳转到人格详情页
        await router.push(
          `${ROUTES.PERSONA_DETAIL.replace(":personaId", persona.id)}`,
        );

        return { success: true, data: persona };
      } else {
        error.value = response.message || "创建人格失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "创建人格失败";
      return { success: false, message: error.value };
    } finally {
      isSaving.value = false;
    }
  };

  /**
   * 更新人格
   */
  const updatePersona = async (
    personaId: string,
    data: UpdatePersonaRequest,
  ) => {
    try {
      isSaving.value = true;
      error.value = null;

      const response = await personaApiService.updatePersona(personaId, data);

      if (response.success) {
        const persona = response.data;
        personaStore.updatePersona(persona);

        if (currentPersona.value?.id === personaId) {
          personaStore.setCurrentPersona(persona);
        }

        return { success: true, data: persona };
      } else {
        error.value = response.message || "更新人格失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "更新人格失败";
      return { success: false, message: error.value };
    } finally {
      isSaving.value = false;
    }
  };

  /**
   * 删除人格
   */
  const deletePersona = async (personaId: string) => {
    try {
      const response = await personaApiService.deletePersona(personaId);

      if (response.success) {
        personaStore.removePersona(personaId);

        // 如果删除的是当前人格，清除当前人格
        if (currentPersona.value?.id === personaId) {
          personaStore.setCurrentPersona(null);
        }

        return { success: true };
      } else {
        error.value = response.message || "删除人格失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "删除人格失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 收藏/取消收藏人格
   */
  const toggleFavorite = async (personaId: string) => {
    try {
      const isFavorited = favoritePersonas.value.some(
        (p) => p.id === personaId,
      );

      const response = isFavorited
        ? await personaApiService.unfavoritePersona(personaId)
        : await personaApiService.favoritePersona(personaId);

      if (response.success) {
        if (isFavorited) {
          personaStore.removeFromFavorites(personaId);
        } else {
          const persona = personas.value.find((p) => p.id === personaId);
          if (persona) {
            personaStore.addToFavorites(persona);
          }
        }

        return { success: true, isFavorited: !isFavorited };
      } else {
        error.value = response.message || "操作失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "操作失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 评分人格
   */
  const ratePersona = async (personaId: string, rating: number) => {
    try {
      const response = await personaApiService.ratePersona(personaId, {
        rating,
      });

      if (response.success) {
        // 更新本地人格评分
        const persona = personas.value.find((p) => p.id === personaId);
        if (persona) {
          personaStore.updatePersona({
            ...persona,
            stats: {
              ...persona.stats,
              averageRating: response.data.averageRating,
              totalRatings: response.data.totalRatings,
            },
          });
        }

        return { success: true, data: response.data };
      } else {
        error.value = response.message || "评分失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "评分失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 复制人格
   */
  const clonePersona = async (personaId: string, name?: string) => {
    try {
      isSaving.value = true;
      error.value = null;

      const response = await personaApiService.clonePersona(personaId, {
        name,
      });

      if (response.success) {
        const persona = response.data;
        personaStore.addPersona(persona);
        personaStore.addToMyPersonas(persona);

        return { success: true, data: persona };
      } else {
        error.value = response.message || "复制人格失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "复制人格失败";
      return { success: false, message: error.value };
    } finally {
      isSaving.value = false;
    }
  };

  /**
   * 分享人格
   */
  const sharePersona = async (personaId: string) => {
    try {
      const response = await personaApiService.sharePersona(personaId);

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "分享失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "分享失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 上传人格头像
   */
  const uploadAvatar = async (personaId: string, file: File) => {
    try {
      const response = await personaApiService.uploadAvatar(personaId, file);

      if (response.success) {
        // 更新本地人格头像
        const persona = personas.value.find((p) => p.id === personaId);
        if (persona) {
          personaStore.updatePersona({
            ...persona,
            avatar: response.data.avatar,
          });
        }

        return { success: true, data: response.data };
      } else {
        error.value = response.message || "上传失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "上传失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 加载我的人格
   */
  const loadMyPersonas = async (page: number = 1, limit: number = 20) => {
    try {
      isLoading.value = true;
      error.value = null;

      const response = await personaApiService.getMyPersonas({ page, limit });

      if (response.success) {
        if (page === 1) {
          personaStore.setMyPersonas(response.data.personas);
        } else {
          personaStore.addToMyPersonas(response.data.personas);
        }

        return { success: true, data: response.data };
      } else {
        error.value = response.message || "加载失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "加载失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 加载收藏的人格
   */
  const loadFavoritePersonas = async (page: number = 1, limit: number = 20) => {
    try {
      isLoading.value = true;
      error.value = null;

      const response = await personaApiService.getFavoritePersonas({
        page,
        limit,
      });

      if (response.success) {
        if (page === 1) {
          personaStore.setFavoritePersonas(response.data.personas);
        } else {
          personaStore.addToFavorites(response.data.personas);
        }

        return { success: true, data: response.data };
      } else {
        error.value = response.message || "加载失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "加载失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 获取推荐人格
   */
  const getRecommendedPersonas = async (limit: number = 10) => {
    try {
      const response = await personaApiService.getRecommendedPersonas({
        limit,
      });

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "获取推荐失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "获取推荐失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 获取热门人格
   */
  const getPopularPersonas = async (limit: number = 10) => {
    try {
      const response = await personaApiService.getPopularPersonas({ limit });

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "获取热门人格失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "获取热门人格失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 设置过滤条件
   */
  const setFilter = (type?: string, tags?: string[]) => {
    if (type !== undefined) selectedType.value = type;
    if (tags !== undefined) selectedTags.value = tags;
  };

  /**
   * 清除过滤条件
   */
  const clearFilters = () => {
    selectedType.value = null;
    selectedTags.value = [];
    searchQuery.value = "";
  };

  /**
   * 设置排序
   */
  const setSorting = (field: string, order: "asc" | "desc" = "desc") => {
    sortBy.value = field;
    sortOrder.value = order;
  };

  /**
   * 检查是否为收藏的人格
   */
  const isFavorited = (personaId: string) => {
    return favoritePersonas.value.some((p) => p.id === personaId);
  };

  /**
   * 检查是否为我的人格
   */
  const isMyPersona = (personaId: string) => {
    return myPersonas.value.some((p) => p.id === personaId);
  };

  // 监听搜索条件变化，自动重新加载
  watch([selectedType, selectedTags, sortBy, sortOrder], () => {
    loadPersonas({ page: 1 });
  });

  return {
    // 状态
    isLoading,
    isSaving,
    error,
    searchQuery,
    selectedTags,
    selectedType,
    sortBy,
    sortOrder,
    personas,
    currentPersona,
    favoritePersonas,
    recentPersonas,
    myPersonas,
    hasMorePersonas,
    totalPersonas,
    filteredPersonas,

    // 方法
    loadPersonas,
    searchPersonas,
    loadPersona,
    createPersona,
    updatePersona,
    deletePersona,
    toggleFavorite,
    ratePersona,
    clonePersona,
    sharePersona,
    uploadAvatar,
    loadMyPersonas,
    loadFavoritePersonas,
    getRecommendedPersonas,
    getPopularPersonas,
    setFilter,
    clearFilters,
    setSorting,
    isFavorited,
    isMyPersona,
  };
}
